package com.ley.springboot.seed.advice;

import com.ley.springboot.seed.exception.ServiceException;
import com.ley.springboot.seed.utils.web.ResponseUtils;
import com.ley.springboot.seed.utils.web.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局捕获异常
 *
 * @author author
 **/
@Slf4j
@Order
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(ServiceException.class)
    public void handleError(ServiceException e, HttpServletResponse response) {
        log.error(e.getMessage(), e);
        ResponseUtils.responseResult(response, ResultEntity.error("系统错误，请联系管理员。"));
    }

    @ExceptionHandler(Throwable.class)
    public void handleError(Throwable e, HttpServletResponse response) {
        log.error(e.getMessage(), e);
        ResponseUtils.responseResult(response, ResultEntity.error("系统错误，请联系管理员。"));
    }
}
